<?php

class Lib_Code
{
    const CODE_EXPIRE = 600; //验证码失效时间
    const SECURITY = 3;
    private static $mem_key_pre = '__MobileVerify_KEY_';


    /**
     * 生成验证码
     */
    public static function getCode($length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = mt_rand(pow(10, $length-1), pow(10, $length) - 1);
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }

    /**
     * 保存验证码
     * @param $mobile
     * @param $code
     * @param $scene
     */
    public static function saveCode($mobile, $code)
    {
        $memKey = self::getMemKey($mobile);
        Func_Cachefunc::getInstance()->set($memKey, $code, self::CODE_EXPIRE);
    }

    /**
     * 校验验证码
     * @param $mobile
     * @param $code
     * @param $scene
     * @return bool
     */
    public static function verifyCode($mobile, $code)
    {
        $memKey = self::getMemKey($mobile);
        $exist_code = Func_Cachefunc::getInstance()->get($memKey);
        if (empty($exist_code)) {
            return false;
        }
        if (!$exist_code || $exist_code != $code) {
            return false;
        }
        //验证通过后失效
        Func_Cachefunc::getInstance()->delete($memKey);
        return true;
    }

    public static function getMemKey($mobile)
    {
        return self::$mem_key_pre . 'MEDIATE_' . $mobile;
    }

}